﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MyWeb.ServiceBus.Model;
using MyWeb.ServiceBus.Model.Dto;
using MyWeb.ServiceBus.Model.Models;
using MyWeb.ServiceBus.Services;
using MyWeb.ServiceBus.Services.Db;
using System.Linq;
using System.Linq.Expressions;

namespace MyWeb.ServiceBus.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class SubServerController : ControllerBase
    {
        private readonly ISubServerService service;
        private readonly Context db;
        public SubServerController(ISubServerService subServer,Context context)
        {
            service = subServer;
            db = context;
        }

        [HttpGet]
        public IActionResult Get()
        {
            return Ok(service.Query(a=>1==1));
        }
        /// <summary>
        /// 获取已订阅列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <param name="appId"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetPage(int page,int pageSize, long appId = 0, string key = "")
        {
            var request = new SubServerDto()
            {
                Pagination = new PageModel()
                {
                    Page = page,
                    PageSize = pageSize,
                },
                AppId = appId,
                Key = key
            };
            var data = await service.QueryPageAsync(request);
            
            var pageData = new PageModel(page, request.Pagination.DataCount, pageSize, data);

            return ApiResult.SUCCESS(pageData);
        }
        /// <summary>
        /// 获取需要订阅的列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <param name="appId"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetServerList(int page, int pageSize, long appId = 0, string key = "")
        {
            var linq = from a in db.SysService
                       join g in db.Gateway on a.Id equals g.ServiceId
                       join s in db.SubServer on new{ GatewayId = g.Id, AppId = appId } equals new{ s.GatewayId, s.AppId } into joinedTable
                       from s in joinedTable.DefaultIfEmpty()
                       select new
                       {
                           ServiceId = a.Id,
                           a.Code,
                           a.Name,
                           a.Type,
                           g.Id,
                           g.Version,
                           isSelect= s != null ? true:false
                       };

            long count = linq.LongCount();
            var data = await linq.Skip((page - 1) * pageSize).Take(pageSize).ToListAsync();
            var pageData = new PageModel(page, (int)count, pageSize, data);
            return ApiResult.SUCCESS(pageData);
        }

        [HttpPost]
        public ApiResult SubServer(SubList sub)
        {
            var old = (from s in db.SubServer
                       where sub.ids.Contains(s.GatewayId)
                       select s.GatewayId).ToList();

            //查询订阅的服务
            var server = (from g in db.Gateway
                          where sub.ids.Contains(g.Id) && !old.Contains(g.Id)
                          select g).ToList();

            foreach(var item in server)
            {
                var subServer = new SubServer()
                {
                    AppId = sub.appid,
                    ServerId = item.ServiceId,
                    //ServerCode
                    GatewayId = item.Id,
                    Version = item.Version,
                    SubTime = DateTime.Now,
                    CreateDate = DateTime.Now
                };
                service.Add(subServer);
            }
            return ApiResult.SUCCESS();
        }

        /// <summary>
        /// 取消订阅
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<ApiResult> CanselSub(long id)
        {
            var sub = service.Query(s => s.Id == id).First();

            await service.DeleteAsync(sub);
            return ApiResult.SUCCESS();
            string str = $"{sub.Version}";
        }
    }
    public class SubList
    {
        public long appid { get; set; }
        public List<long> ids { get; set; }
    }
}
